import React, { useState, useEffect,useRef } from "react";
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm/index'
import { Form ,Button,notification,Select,Divider,Modal,Pagination,Empty,message} from 'antd';
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'

import { Menu, Dropdown, Space} from 'antd';
import { DownOutlined ,ExclamationCircleOutlined} from '@ant-design/icons'

import {findTestPaper,publishingTask,getPlanData,queryTaskRedisByPage,addTestPaper,getMapping} from 'api/index'

import PlanTable from './table'
import { withRouter } from "react-router-dom";

const paginationStyle = {float:'right',margin:'30px 20px 0 0', position: 'absolute',
bottom: '20px',
right: '30px'}

// 新增弹框
const AddLink = (props) =>{
const {isModalVisible, setIsModalVisible,dictionaries,userName} = props
const [form] = Form.useForm();//新增试卷
const loading = useRef(false)

  // 新增表单
const newWordItem = [
  {label: '用户级别',type:'input', name: 'paperName' , span: 20 ,rules:[
    {
      required: true,
      message: '请输入试卷名称'
    },
  ]},
  {label: '环节类型', name: 'levelId', span: 20,rules:[
    {
      required: true,
      message: '请选择级别'
    },
  ],render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
  }},
]

const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    form.validateFields().then(async()=>{

    

      const data = {
        paperName: form.getFieldValue().paperName,
        levelId: form.getFieldValue().levelId,
        type: form.getFieldValue().type,
        }
        
       await addTestPaper(data)

       notification.success({
          message: '新增成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      
      form.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      notification.warning({
        message: '检查必填项',
        duration:1.5
      });
    }).finally(()=>{
      loading.current=false
    })
};

  const handleCancel = () => {
    form.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal width={700} title="新增环节" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={form} labelCol={8} formItem={newWordItem} />
   </Modal>
} 
// 编辑弹框
const EditPaper = (props) =>{
const {isModalVisible, setIsModalVisible,dictionaries,userName,editForm} = props
const loading = useRef(false)

  // 表单
const newWordItem = [
  {label: '试卷名称',type:'input', name: 'paperName' , span: 20 ,rules:[
    {
      required: true,
      message: '请输入试卷名称'
    },
  ]},
  {label: '级别', name: 'levelId', span: 20,rules:[
    {
      required: true,
      message: '请选择级别'
    },
  ],render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
  }},
  {label: '试卷类型', name: 'type', span: 20,rules:[
    {
      required: true,
      message: '请选择试卷类型'
    },
  ],render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择试卷类型'}
    options={[{id:'1',dictValue:'定级测试'},{id:'2',dictValue:'升级测试'}]}
  >
  </Select>
  }},
]

const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    editForm.validateFields().then(async()=>{

      const data = {
        paperName: editForm.getFieldValue().paperName,
        levelId: editForm.getFieldValue().levelId,
        type: editForm.getFieldValue().type,
        id: editForm.getFieldValue().id,
        }
        
       await addTestPaper(data)

       notification.success({
          message: '编辑成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      
      editForm.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      notification.warning({
        message: '检查必填项',
        duration:1.5
      });
    }).finally(()=>{
      loading.current=false
    })
};

  const handleCancel = () => {
    editForm.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal width={700} title="编辑试卷" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={editForm} labelCol={8} formItem={newWordItem} />
   </Modal>
} 


function PlanLibrary(props) {
const {dictionaries} = props
// 数据
const [loading,setLoading] = useState(false) //加载
const [expand,setExpand] = useState(true) //表单伸缩
const [total,setTotal] = useState(0) //总数量
const [id,setId] = useState('')
const [isModalVisible, setIsModalVisible] = useState(false)
const [isModalVisibleTask, setIsModalVisibleTask] = useState(false)
const [isModalVisibleStatus, setIsModalVisibleStatus] = useState(false)
const [isModalVisiblePreview, setIsModalVisiblePreview] = useState(false)
const [isModalVisibleEdit, setIsModalVisibleEdit] = useState(false)
const [selectData, setSelectData] = useState([])
const [form] = Form.useForm();//搜索列表
const [editForm] = Form.useForm();//


const [getLevelAppOptions,setLevelApp] = useState([])

const getAppLevel = async() => {
  const res = await getMapping({ pageSize: 50, currPage: 1 })
  const data = res.result.records.filter(i => i.levelId === (form.getFieldValue().levelId||106)) ? res.result.records.filter(i => i.levelId === (form.getFieldValue().levelId||106))[0]?.levelAppId : []

  if (!data || data.length === 0) {
    setLevelApp([])
  } else {
    setLevelApp(dictionaries.LevelApp.map(i => {
      if (data.includes(i.id)) {
        return i
      }
    }).filter(i => i))
  }
}

const levelChange = (e) => {
  getAppLevel()
}

// 表单数据
const formItem = [
  {label: '文件名称',type:'input', name: 'fileName', span:4 },
  {label: '级别', name: 'levelId' , span: 5,render: () => {
    return <Select
    defaultValue={106}
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    onChange={levelChange}
    options={dictionaries.Level}
  >
  </Select>
} },
  {label: '用户级别', name: 'levelAppId' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    multiple
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={getLevelAppOptions}
  >
  </Select>
} },
  {label: '环节名称', name: 'taskTypeId' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.linkType}
  >
  </Select>
} },
  {label: '环节展示', name: 'linkTypeShow' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择展示'}
    options={[{ id: 1, dictValue: '仅展示环节' }, { id: 2, dictValue: '展示环节所在任务' }]}
  >
  </Select>
} },
  {label: '任务号', name: 'serialNumber' , span: 4,render: () => {
    return <Select
    allowClear
    optionFilterProp="id"
    showSearch
    fieldNames={{value:'id',label:'id'}}
    placeholder={'请选择任务号'}
    options={Array(100).fill().map((i,j)=>{
      return {id:j+1}
    })}
  >
  </Select>
} },
  {label: '空值', name: 'isNull' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择为空数据'}
    options={[{id:1,dictValue:'目标单词为空'},{id:2,dictValue:'目标句子为空'}]}
  >
  </Select>
} },
{label: '目标单词',type:'input', name: 'targetWord', span: 5 },
{label: '目标句子',type:'input', name: 'targetSentence', span: 5 },
]
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])



// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='plan/planLibrary')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='plan/planLibrary')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  getAppLevel()
  },[]) // eslint-disable-line react-hooks/exhaustive-deps


// 切换发布草稿素材
useEffect(()=>{
  // 获取数据
  getNewList()

  
},[props.examineStatus]) // eslint-disable-line react-hooks/exhaustive-deps

// 方法
// 1.获取数据
const getNewList=(value)=>{

   setLoading(true)

  // 缓存数据
   const data = {
     pagination: value&&value.pageSize?value:pagination,
     form:form.getFieldValue()
  }

    props.setPageDataFn('plan/planLibrary',data) 

    const initialData = async () => {

      const params = {
        currPage:value&&value.pageSize?value.current:pagination.current,
        pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
        fileName: form.getFieldValue().name,
        levelId: form.getFieldValue().levelId || 106,
        taskTypeId: form.getFieldValue().linkTypeId,
        linkTypeShow: form.getFieldValue().linkTypeShow,
        targetSentence: form.getFieldValue().targetSentence,
        targetWord: form.getFieldValue().targetWord,
        levelAppId: form.getFieldValue().levelAppId,
        serialNumber: form.getFieldValue().serialNumber
      }
        
      if (form.getFieldValue().isNull === 1) {
        params.targetWordIsNull = true
      } else if (form.getFieldValue().isNull === 2) {
        params.targetSentenceIsNull = true
      }


      if(!props.examineStatus){
        const res = await getPlanData(params)
        setDataSource(res.result.records||[])
        setTotal(res.result.total||0)
      } else {
        const res = await queryTaskRedisByPage(params)
        setDataSource(res.result.records||[])
        setTotal(res.result.total||0)
      }
       

   
    
      setLoading(false)
    
    }
  
    initialData()
    }
 // 2.重置表单
 const resetForm=()=>{
   form.resetFields()
   setPagination({
    current:1,
    pageSize:20
  })
   getNewList()
 }
// 1.新增环节
const addLink = () => {

}
// 2.升级规则
const planRule = () => {

}
// 3.手动发布
const publishPlan = async() => {
  await publishingTask()
  message.success('手动发布成功')
}
// 4.更多操作
const moreOperation = (value) =>{
  // 判断是否选择了数据
  const data1 = dataSource.filter(i=>i.checkTask)

  const data2 = []
  dataSource.forEach(i => {
    i.linkList.forEach(x => {
      if (x.checkLink) {
        data2.push(x)
      }
    })
  })
  
  switch (value.key) {
    case 'removeTask':
    break
    case 'cloneTask':
    break
    case 'removeLink':
    break
    case 'taskSubject':
      if (data2.filter(i => i.type === 'LESSON' || i.type === 'IR_BOOK').length === 0) {
        message.error('至少选择一项精读和主题课环节')
        return
      }
      const taskInfo = [data2.filter(i => i.type === 'LESSON' || i.type === 'IR_BOOK').map(i => {
        return { fileName: i.fileName, id: i.dataId, type: i.type }
      }), dataSource.filter(i => i.checkLink).map(i => {
        return { id: i.id, levelId: i.levelId }
      })[0]].filter(i=>i)

      if(data1.length!==1){
        message.error('任务只能选一个')
        return
      }
      props.history.push({
        pathname:'/view/plan/planSubject',state:[taskInfo,data1]
      })
     break
   default:
     return
  }
}
// 更多操作
const menu = (
 <Menu
    onClick={moreOperation}
    items={[
      {
        label: '删除环节',
        key: 'removeLink',
      },
      {
        label: '删除任务',
        key: 'removeTask',
      },
      {
        label: '复制任务',
        key: 'cloneTask',
      },
      {
        label: '任务重排',
        key: 'sortTask',
      },
      {
        label: '配置题目',
        key: 'taskSubject',
      },
    ]}
  />
);
//5. 切换分页
const onChange = (value,size) =>{
    setPagination({
      current: value,
      pageSize: size
    })
    getNewList({
      current: value,
      pageSize: size
    })
  }
// 展示总数
const showTotal =()=>{
  return '共计'+ total +'条'
}
return <div className="app-content animate__animated animate__fadeIn">
    {/* 表单 */}
    <LlxForm form={form} formItem={expand?formItem:formItem.filter((i,j)=>j<5)}/>
    {/* 操作按钮 */}
    <div className="operate-btn">
     <div>
       {
          !props.examineStatus ? 
          <>
           <Button  onClick={addLink} type='primary' className='animate__animated animate__fadeInLeft'>新增环节</Button>
           <Button  onClick={publishPlan} type='primary' className='animate__animated animate__fadeInLeft'>手动发布</Button>
           <Button  onClick={planRule} type='primary' className='animate__animated animate__fadeInLeft'>升级规则</Button>
          </>:''
       }
       {
         !props.examineStatus ? <Dropdown overlay={menu}>
         <Button  className='animate__animated animate__fadeInLeft'>
           <Space>
            更多操作
           <DownOutlined />
          </Space>
        </Button>
       </Dropdown>:''
       }
       </div>
       <div>
         <Button  onClick={getNewList} type='primary' className='animate__animated animate__fadeInRight'>查询</Button>
          <Button  type='primary' onClick={resetForm} className='animate__animated animate__fadeInRight'>重置</Button>
          <Button  type='link' onClick={()=>setExpand(i=>!i)} className='animate__animated animate__fadeInRight'>{expand?'收起':'展开'}</Button>
       </div>
    </div>

    <Divider />
    {/* 表格 */}
    {
      dataSource.length?<PlanTable getNewList={getNewList} loading={loading} data={dataSource}></PlanTable>:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
    }

    <Pagination onChange={onChange} showTotal={showTotal} style={paginationStyle} pageSize={pagination.pageSize} current={pagination.current} total={total} />
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {userBtnRole:state.userBtnRole,tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(withRouter(PlanLibrary))
